﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace wd_20_findwindow
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// ref
    /// https://blog.csdn.net/qq_40096897/article/details/124345749
    /// 
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        //根据窗口类型或者窗口标题获取窗口句柄
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        //根据父窗口句柄、子窗口句柄、窗口类型、窗口标题 获取句柄
        [DllImport("user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
        private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
        /// <summary>
        /// 向指定句柄的窗口发送消息
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="Msg">消息类型</param>
        /// <param name="wParam">消息1</param>
        /// <param name="lParam">消息2</param>
        /// <returns></returns>
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);

        //将指定句柄的窗口置顶
        [DllImport("User32.dll", EntryPoint = "SetForegroundWindow")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            IntPtr LoginWnd = new IntPtr(0);
            //LoginWnd = FindWindow("Intermediate D3D Window", "");
            //LoginWnd = FindWindow("Everything", null);
            //LoginWnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Chrome_WidgetWin_1", null);  //bug for vysor.exe，2022-09-28 15:27:06
            LoginWnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, "Vysor");  //bug for vysor.exe，2022-09-28 15:27:06

            Trace.WriteLine(string.Format("addr: {0}\n", LoginWnd));
        }
    }
}
